package com.zzyy.study.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @auther zzyy
 * @create 2024-09-21 20:24
 */
@Component
public class MinIoUtil
{

    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String minIOUrl;

    /**
     * 上传文件
     * @param fileName
     * @param inputStream
     * @param contentType
     * @return
     */
    public String upload(String fileName, InputStream inputStream, String contentType)
            throws ServerException, InsufficientDataException, ErrorResponseException,
            IOException, NoSuchAlgorithmException, InvalidKeyException,
            InvalidResponseException, XmlParserException, InternalException
    {

        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());

        if (!isExist)
        {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        // 文件上传
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(inputStream, -1, 10485760)
                .contentType(contentType)
                .build());

        // 返回 URL 地址 V1
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .method(Method.GET)
                .build());

        // 返回 URL 地址 V2
        //return minIOUrl + "/" + bucketName + "/" + fileName;
    }

}

